<?php
/**
 * Created by xun at 2020/5/17
 */

namespace app\base;

class MysqlConnection
{

    use \app\storage\Singleton;

    public $connectionCount = 0;

    private $connections = [];

    private $config;

    public function __construct($config)
    {
        $this->config = $config;
    }

    public function addConnection()
    {
        $mysql = new \Mysqli(
            $this->config['host'],
            $this->config['user'],
            $this->config['password'],
            $this->config['db']
        );
        echo 'add ' . $mysql->thread_id . ' into pool ' . PHP_EOL;
        $this->connections[$mysql->thread_id] = $mysql;
        $this->connectionCount++;
        return $mysql->thread_id;
    }

    public function getConnection($thread_id = 0)
    {
        if ($thread_id == 0) {
            $this->addConnection();
        }
        return $this->connections[$thread_id];
    }

    public function releaseConnection($thread_id)
    {
        unset($this->connections[$thread_id]);
        $this->connectionCount--;
    }

    public function clear()
    {
        foreach ($this->connections as $k => $v) {
            $this->releaseConnection($k);
        }
    }

}